package com.redstar.study;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import com.actionbarsherlock.app.SherlockActivity;
import com.deaux.fan.FanView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.SQLException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Quiz extends SherlockActivity {

	// UI widgets
	private TextView QuestionTV;
	private TextView AnswerTV;
	private TextView ProgressTv;
	private RatingBar RatingB;
	private Button Answer1;
	private Button Answer2;
	private Button Answer3;
	private Button Answer4;
	private Button Next;
	
	// listeners
	private OnClickListener AnswerListener;
	
	// words and database
	private DataBaseHelper myDbHelper;
	private List<Word> listOfWords;
	
	//quiz progress tracking	
	private int currentWord = 0;
	private int limit = 0;
	private int currentQuestion = 0;
	private int RightAnswer = 0;
	
	// tacking + preferences 
	private GoogleAnalyticsTracker tracker;	
	private SharedPreferences preferences;
	private boolean JAPANESE_ANSWERS;
	private boolean SKIP_LEARNT;
	
	// dialogs and toasts
	static final int DIALOG_QUIZ_FINISHED = 0;
	static final int DIALOG_NO_WORDS = 3;
	static final int SHOW_ANSWER_CORRECT = 1;
	static final int SHOW_ANSWER_WRONG = 2;
	
	private boolean ANSWER_LOCK = false;
	
	//Answer toasts
	private Toast toast;
	private TextView toastText;
	private ImageView toastImage;
	
	private FanView fan;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test);
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setTitle("Quiz");

		fan = (FanView) findViewById(R.id.fan_view);
		fan.setViews(R.layout.quiz, R.layout.fan);
		
		String[] fanOptions = getResources().getStringArray(R.array.list);    
		FanMenuAdapter fanAdapter = new FanMenuAdapter(this, fanOptions);
		
		ListView fanList = (ListView) findViewById(R.id.fan_list);
		fanList.setAdapter(fanAdapter);
		
	/*	fanList.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long ID) {
				// TODO Auto-generated method stub
				
				Intent i;
				
				switch (position) {
				case 0:
					i = new Intent(Quiz.this, PracticePreferences.class);
					break;
				case 1:
					i = new Intent(Quiz.this, QuizPreferences.class);
					break;
				case 2:
					i = new Intent(Quiz.this, Dictionary.class);
					break;
				default:
					i = new Intent();
				}
				Quiz.this.startActivity(i);
				
			}
			
		});	*/
		
		// get preferences
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		// get the amount of the questions to be asked from preferences
		limit = Integer.parseInt(preferences.getString("Questions", "30"));
		JAPANESE_ANSWERS = preferences.getBoolean("Japanese Answers", false);
		SKIP_LEARNT = preferences.getBoolean("Skip Learnt", true);
		
		myDbHelper = createDB();
		listOfWords = myDbHelper.getAllVocab(SKIP_LEARNT);
		
		if(listOfWords.isEmpty()){
			showDialog(DIALOG_NO_WORDS);
		}else{
			setupViews();	
			nextQuestion();			
		}
		
	    tracker = GoogleAnalyticsTracker.getInstance();
	    // Start the tracker in manual dispatch mode...
	    tracker.startNewSession("UA-29340571-1",20, this);		
		tracker.trackPageView("/Quiz");
	}



	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.quiz);
		setupViews();
	}	
	
	private void setupViews() {
		// UI Views
		ProgressTv = (TextView) findViewById(R.id.QZProgressTV);
		QuestionTV = (TextView) findViewById(R.id.QZQuestionTV);
		AnswerTV = (TextView) findViewById(R.id.QZAnswerTV);
		AnswerTV.setVisibility(View.INVISIBLE);
		RatingB = (RatingBar) findViewById(R.id.QZRatingBar);
		
		Answer1 = (Button) findViewById(R.id.QZAnswer1);
		Answer2 = (Button) findViewById(R.id.QZAnswer2);
		Answer3 = (Button) findViewById(R.id.QZAnswer3);
		Answer4 = (Button) findViewById(R.id.QZAnswer4);

		AnswerListener = new OnClickListener(){
			public void onClick(View v) {
				ANSWER_LOCK = true;
				disableButtons();
				//cast the view
				Button B = (Button) v;
				//highlight users answer
				B.setBackgroundResource(R.drawable.the_chosen_card);
				
				Word TempWord = listOfWords.get(currentWord);
				double TempRating = TempWord.getRating();
				
				//if correct
				if(B.getText().equals(AnswerTV.getText())){
					if(TempWord.getRating()<5){
						TempRating += 1;
						RightAnswer++;
						Next.setBackgroundDrawable(getResources().getDrawable(R.drawable.next_correct));
						toastImage.setImageResource(R.drawable.correct);
						toastText.setText(R.string.correct);
						toast.show(); 				
					}
				}else{ // if wrong
					if(TempWord.getRating()>=0){
						TempRating -= 1;
						Next.setBackgroundDrawable(getResources().getDrawable(R.drawable.next_wrong));
						toastImage.setImageResource(R.drawable.wrong);
						toastText.setText(R.string.wrong);
						toast.show(); 	
					}
				}
				//set new rating
				listOfWords.get(currentWord).setRating(TempRating);
				myDbHelper.setRating(TempWord, TempRating);
				RatingB.setRating((float) TempRating);				
				// TODO Auto-generated method stub
			}
		};
		
		Answer1.setOnClickListener(AnswerListener);
		Answer2.setOnClickListener(AnswerListener);
		Answer3.setOnClickListener(AnswerListener);
		Answer4.setOnClickListener(AnswerListener);		
		
		Next = (Button) findViewById(R.id.Next);
		Next.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				ANSWER_LOCK = false;
				// TODO Auto-generated method stub
				if(toast != null){
					//cancel answer toast if its showing
					toast.cancel();
				}
	          	if(currentQuestion==limit){
	          		showDialog(DIALOG_QUIZ_FINISHED);
				}
				else{
					nextQuestion();
				}
			}		
		});
		
		setQuestion();	
		
		// Answer toast
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
		                               (ViewGroup) findViewById(R.id.toast_layout_root));
		
		toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(layout);
		toastText = (TextView) layout.findViewById(R.id.toastText);
		toastImage = (ImageView) layout.findViewById(R.id.toastImage);
	}

	private void disableButtons() {
		// TODO Auto-generated method stub
		AnswerTV.setVisibility(View.VISIBLE);
		Answer1.setEnabled(false);
		Answer2.setEnabled(false);
		Answer3.setEnabled(false);
		Answer4.setEnabled(false);	
		Next.setEnabled(true);
	}	
	
	private void nextQuestion() {
		// TODO Auto-generated method stub
		currentWord = new Random().nextInt(listOfWords.size()-1);
		currentQuestion++;
		setQuestion();		
	}		
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
	    switch (item.getItemId()) {
        case android.R.id.home:
            // display menu
        	displayMenu();

            return true;
        default:
            return super.onOptionsItemSelected(item);
	    }
	}
	
	private void displayMenu() {
		// TODO Auto-generated method stub
		fan.showMenu();	
	}
	
    public void unclick(View v) {
    	System.out.println("CLOSE");
    	fan.showMenu();
    }
    
    public void click(View v) {
    	System.out.println("OPEN");
    	fan.showMenu();
    }	
	private void setQuestion() {
		// TODO Auto-generated method stub
		ProgressTv.setText(currentQuestion + "/" + limit);
		if(JAPANESE_ANSWERS){
			QuestionTV.setText(listOfWords.get(currentWord).getDefinition());
			setJapaneseTextView(AnswerTV, currentWord);
		}else{
			setJapaneseTextView(QuestionTV, currentWord);
			AnswerTV.setText(listOfWords.get(currentWord).getDefinition());
		}
		
		//KanaTv.setText(listOfWords.get(currentWord).getKana());
		
		RatingB.setRating((float) listOfWords.get(currentWord).getRating());
		
		if(ANSWER_LOCK){
			disableButtons();
		}else{
			enableButtons();
		}
		
		if(JAPANESE_ANSWERS){
			//function pass  in button and word
			int random = new Random().nextInt(listOfWords.size());
			setAnswerButton(Answer1, random);
			random = new Random().nextInt(listOfWords.size());
			setAnswerButton(Answer2, random);
			random = new Random().nextInt(listOfWords.size());
			setAnswerButton(Answer3, random);
			random = new Random().nextInt(listOfWords.size());
			setAnswerButton(Answer4, random);
			
			switch (new Random().nextInt(4)) {
			case 0:
				setAnswerButton(Answer1,currentWord);
				break;
			case 1:
				setAnswerButton(Answer2,currentWord);
				break;
			case 2:
				setAnswerButton(Answer3,currentWord);
				break;
			case 3:
				setAnswerButton(Answer4,currentWord);
				break;
			}		
		}
		else{
			Answer1.setText(listOfWords.get(new Random().nextInt(listOfWords.size())).getDefinition());
			Answer2.setText(listOfWords.get(new Random().nextInt(listOfWords.size())).getDefinition());
			Answer3.setText(listOfWords.get(new Random().nextInt(listOfWords.size())).getDefinition());
			Answer4.setText(listOfWords.get(new Random().nextInt(listOfWords.size())).getDefinition());			

			switch (new Random().nextInt(4)) {
			case 0:
				Answer1.setText(listOfWords.get(currentWord).getDefinition());
				break;
			case 1:
				Answer2.setText(listOfWords.get(currentWord).getDefinition());
				break;
			case 2:
				Answer3.setText(listOfWords.get(currentWord).getDefinition());
				break;
			case 3:
				Answer4.setText(listOfWords.get(currentWord).getDefinition());
				break;
			}		
		}
	}
	
	private void setAnswerButton(Button ans, int word) {
		String kanji = listOfWords.get(word).getKanji();
		String kana =  listOfWords.get(word).getKana();
		
		if(kanji==null){
			ans.setText(kana);
		}
		else{
			ans.setText(kanji + "\n" + kana);
		}
	}

	private void setJapaneseTextView(TextView ans, int word) {
		String kanji = listOfWords.get(word).getKanji();
		String kana =  listOfWords.get(word).getKana();
		
		if(kanji==null){
			ans.setText(kana);
		}
		else{
			ans.setText(kanji + "\n" + kana);
		}
	}

	protected Dialog onCreateDialog(int id) {
		Dialog dialog = new Dialog(this);//<=====THIS
	    
	    switch(id) {
	    case DIALOG_QUIZ_FINISHED:
	    	disableButtons();
	    	dialog = new Dialog(this, R.style.Theme_Sherlock_Dialog);
	    	dialog.setContentView(R.layout.result_dialog);
	    	dialog.setTitle("Well done!!!");
	    	float percent = ((float) RightAnswer / (float) limit) * 100;
	    	TextView TV = (TextView) dialog.findViewById(R.id.ResultPercentTV);
	    	TV.setText(RightAnswer + "/" + limit +
	    				"\n" + (int) percent + "%\n");
	    	RatingBar Rating = (RatingBar)  dialog.findViewById(R.id.ResultRating);
	    	Rating.setRating((int) percent/20);
	    	Button button = (Button) dialog.findViewById(R.id.ResultBN);
	    	
	    	button.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					Intent i = new Intent(Quiz.this, MainScreen.class);
					Quiz.this.startActivity(i);					
				}
	    		
	    	});
	    	break;
	    	
	    case DIALOG_NO_WORDS:
	    	dialog = new Dialog(this, R.style.Theme_Sherlock_Dialog);
	    	dialog.setContentView(R.layout.result_dialog);
	    	dialog.setTitle("Nothing to practice!!!");
	    	TextView TV1 = (TextView) dialog.findViewById(R.id.ResultPercentTV);
	    	TV1.setText( "You have gotten 5 stars on every word");
	    	RatingBar Rating1 = (RatingBar)  dialog.findViewById(R.id.ResultRating);
	    	Rating1.setVisibility(View.INVISIBLE);
	    	Button button1 = (Button) dialog.findViewById(R.id.ResultBN);
	    	
	    	button1.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					Intent i = new Intent(Quiz.this, MainScreen.class);
					Quiz.this.startActivity(i);					
				}
	    		
	    	});
	    	break;
	    default:
	    	dialog = null;
	    }
	    return dialog;
	}


	
	private void enableButtons(){
		// TODO Auto-generated method stub
		AnswerTV.setVisibility(View.INVISIBLE);
		Answer1.setEnabled(true);
		Answer2.setEnabled(true);
		Answer3.setEnabled(true);
		Answer4.setEnabled(true);	
		
		Answer1.setBackgroundResource(R.drawable.the_card);
		Answer2.setBackgroundResource(R.drawable.the_card);
		Answer3.setBackgroundResource(R.drawable.the_card);
		Answer4.setBackgroundResource(R.drawable.the_card);

		Next.setEnabled(false);
		Next.setBackgroundDrawable(getResources().getDrawable(R.drawable.next_disabled));
	}
	
	private DataBaseHelper createDB() {
		myDbHelper = new DataBaseHelper(this);
		// TODO Auto-generated method stub
		try {
			myDbHelper.createDataBase();
		}
		catch (IOException ioe) { throw new Error("Unable to create database"); }
		
		try { 
			myDbHelper.openDataBase(); 
		}
		catch(SQLException sqle){ throw sqle; }
		
		return myDbHelper;
	}
	
	@Override
    public void onDestroy() {
        super.onDestroy();
        myDbHelper.close();
        // Stop the tracker when it is no longer needed.
        tracker.stopSession();
	}
}
